//
//  LEDownloadManager.m
//  WindRunner
//
//  Created by leeqb on 11/17/14.
//  Copyright (c) 2014 poweropt. All rights reserved.
//

#import "LEDownloadManager.h"
#import "NSString+Hashing.h"

@implementation LEDownloadManager

- (id)init
{
    self = [super init];
    if(self) {
        //_downloadQueue = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (id)initWithTarget:(UIImageView *)target
{
    self = [self init];
    if(self) {
        self.target = target;
    }
    return self;
}

- (void)downLoadImageWithURL:(NSString *)url imagetype:(NSString *)type
{
    if(url && ![url isEqual:[NSNull null]]) {
        url = [url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (url == nil || [url isEqualToString:@""]) {
            return;
        }
        
        url = [NSString stringWithFormat:@"%@%@", IMAGE_URL_PREFIX, url];
        self.filePath = [NSString stringWithFormat:@"%@/tmp/%@/%@",NSHomeDirectory(), type, url.MD5Hash];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        // 判断图片在缓存中是否存在，不存在则需要网络下载，存在时直接获取
        if ([fileManager fileExistsAtPath:self.filePath]) {
            // 获取缓存中的图片
            NSData *imageData = [NSData dataWithContentsOfFile:self.filePath];
            
            if(self.target && [self.target isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView = (UIImageView *)self.target;
                imageView.image = [UIImage imageWithData:imageData];
            } else {
                [self.delegate downloadImage:self downloadFinished:[UIImage imageWithData:imageData]];
            }
        }else{
            // 创建缓存目录
            NSError *error = nil;
            [fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@/tmp/%@",NSHomeDirectory(), type] withIntermediateDirectories:YES attributes:nil error:&error];
            if (error) {
                return;
            }
            // 下载图片
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
            NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
            [connection start];
        }
    }
}

#pragma mark - NSURLConnection delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _imageData = [[NSMutableData alloc] init];
    _response = response;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_imageData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)_response;
    if(response.statusCode == 200) {
        // 缓存图片
        [_imageData writeToFile:self.filePath atomically:NO];
        
        if(self.target && [self.target isKindOfClass:[UIImageView class]]) {
            UIImageView *imageView = (UIImageView *)self.target;
            imageView.image = [UIImage imageWithData:_imageData];
        } else {
            if(self.delegate && [self.delegate respondsToSelector:@selector(downloadImage:downloadFinished:)]) {
                [self.delegate downloadImage:self downloadFinished:[UIImage imageWithData:_imageData]];
            }
        }
    }
}

@end
